<template>
  <div class="salary-container">
    <template>
      <div class="permission-container">
        <div class="app-container">
          <el-card style="margin-bottom: 20px">
            <div style="text-align: right">
              <el-button type="primary" size="small" @click="showDialog({ type: 1, pid: '0' })">添加权限</el-button>
            </div>
          </el-card>
          <!-- 表格 -->
          <el-card>
            <el-table border :data="list" row-key="id">
              <el-table-column label="名称" prop="name" />
              <el-table-column label="标识" prop="code" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button type="text" @click="showDialog({ type: 2, pid: row.id })">添加</el-button>
                  <el-button type="text" @click="showDialogEdit(row.id)">编辑</el-button>
                  <el-button type="text" @click="delPermission(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <!-- 弹窗 -->
          <permission-dialog ref="permissionDialogRef" :visible="visible" :type="type" :pid="pid" @fetch-permission-list="fetchPermissionList" @dialog-close="dialogClose" />
        </div>
      </div>
    </template>
  </div>
</template>
<script>
import { getPermissionList, delPermission } from '@/api/permission'
import transTree from '@/utils/transTree'
import PermissionDialog from './components/PermissionDialog'

export default {
  name: 'Permission',
  components: {
    PermissionDialog
  },
  data() {
    return {
      list: [],
      // 控制弹窗显示与隐藏
      visible: false,
      type: '',
      pid: ''
    }
  },
  created() {
    this.fetchPermissionList()
  },
  methods: {
    async fetchPermissionList() {
      const res = await getPermissionList()
      this.list = transTree(res.data, '0')
    },
    // 打开弹窗
    showDialog({ type, pid }) {
      this.visible = true
      this.type = type
      this.pid = pid
    },
    // 弹窗关闭
    dialogClose() {
      this.visible = false
    },
    showDialogEdit(id) {
      this.visible = true
      this.$refs.permissionDialogRef.fetchPermissionDetail(id)
    },
    // 删除权限点
    delPermission(id) {
      // 1. 询问用户
      this.$confirm('此操作将永久删除该权限点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 2. 调用删除接口
        await delPermission(id)
        // 3. 提示用户
        this.$message.success('删除权限点成功')
        // 4. 刷新列表
        this.fetchPermissionList()
      })
    }
  }
}
</script>

<style>
</style>
